package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.service.IYddLinkService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/ydd_link")
public class YddLinkController {

    @Autowired
    private IYddLinkService linkService;

    //连接详情
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id) {
        //构造器
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.eq(YddLink::getId, Integer.parseInt(id));
        //查询
        YddLink one = linkService.getOne(queryWrapper);
        //判断查询内容是否为空
        if (one != null) {
            //返回内容
            return ResultData.ok("查询详情成功", one);
        }
        //返回失败
        return ResultData.error("查询详情失败");
    }

    //查看全部
    @GetMapping("list")
    public ResultData pageList(String type, String page, String limit) {
        long currentPage = Long.parseLong(page);
        long pageSize = Long.parseLong(limit);
        //分页查询器
        Page<YddLink> yddLinkPage = new Page<YddLink>(currentPage, pageSize);
        //查询构造器
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.eq(StringUtils.isNotEmpty(type), YddLink::getType, type);
        //进行查询
        linkService.page(yddLinkPage, queryWrapper);
        //返回查询结果
        return ResultData.ok("", PageResult.getPage(yddLinkPage));
    }

    //新增数据
    @PostMapping("add")
    public ResultData add(@RequestBody YddLink yddLink) {
        //调用添加
        boolean save = linkService.save(yddLink);
        if (save) {
            //添加成功
            return ResultData.ok("添加成功", yddLink);
        }
        //添加失败
        return ResultData.error("添加失败");
    }

    //修改数据
    @PostMapping("update")
    public ResultData update(@RequestBody YddLink yddLink){
        //判断是否为空
        if (yddLink != null) {
            //不空则进行修改
            linkService.updateById(yddLink);
            return ResultData.ok("修改成功", yddLink);
        }
        //空了就失败
        return ResultData.error("修改失败");
    }


    //删除数据
    @GetMapping("del")
    public ResultData delete(String id) {
        //进行一个判断
        if (StringUtils.isNotEmpty(id)) {
            //将String转化为long
            long longId = Long.parseLong(id);
            //调用方法删除
            boolean b = linkService.removeById(longId);
            //对删除结果进行判断
            if (b) {
                return ResultData.ok("删除成功", null);
            }
        }
        return ResultData.error("删除失败");
    }

}
